// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const $ = db.command.aggregate

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        let {
            conditions
        } = event.data

        // 获取当前日期
        const now = new Date();
        const startOfDay = new Date(now);
        startOfDay.setHours(0, 0, 0, 0);
        const endOfDay = new Date(now);
        endOfDay.setHours(23, 59, 59, 999);

        let query = db.collection('orderList')

        // 查询今日销售数据
        const salesResult = await query.aggregate().match({
                _openid: conditions._openid,
                orderStatus: {
                    $not: {
                        $in: [1, 5], // 查询状态除了待付款和售后以为的订单
                    }
                },
                createTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                },
                payTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                }
            })
            .unwind('$goodsName') // 展开商品名
            .group({
                _id: '$goodsName',
                buyNum: $.sum('$buyNum'),
                orderTotalPrice: $.sum('$orderTotalPrice'),
                memberSales: $.sum({ // 会员消费
                    $cond: {
                        if: {
                            $eq: ['$userInfo.level', 1]
                        },
                        then: '$orderTotalPrice',
                        else: 0
                    }
                }),
                crossBorderMemberSales: $.sum({ // 跨界会员消费
                    $cond: {
                        if: {
                            $eq: ['$userInfo.level', 2]
                        },
                        then: '$orderTotalPrice',
                        else: 0
                    }
                }),
            })
            .sort({
                buyNum: -1
            }) // 按销量降序排序
            .limit(5) // 取销量前5的商品
            .end()

        let salesData = []
        if (salesResult.list.length > 0) {
            salesData = salesResult.list.map(item => {
                return {
                    goodsName: item._id,
                    buyNum: item.buyNum,
                    orderTotalPrice: item.orderTotalPrice,
                    memberSales: item.memberSales,
                    crossBorderMemberSales: item.crossBorderMemberSales,
                }
            })
        }

        // 查询今日优惠券使用情况
        const couponResult = await query.aggregate().match({
                _openid: conditions._openid,
                orderStatus: {
                    $not: {
                        $in: [1, 5], // 查询状态除了待付款和售后以为的订单
                    }
                },
                createTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                },
                payTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                }
            })
            .unwind('$couponName')
            .group({
                _id: '$couponName',
                couponNum: $.sum('$couponNum'),
            })
            .end()

        let couponData = []
        if (couponResult.list.length > 0) {
            couponData = couponResult.list.map(item => {
                return {
                    couponName: item._id,
                    couponNum: item.couponNum,
                }
            })
        }

        return {
            code: 200,
            msg: "操作成功",
            data: {
                salesData,
                couponData,
            }
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
}